package com.zhentao.controller;

import com.zhentao.dto.JwtAuthResponse;
import com.zhentao.dto.LoginDto;
import com.zhentao.dto.RegisterDto;
import com.zhentao.service.AuthService;

import com.zhentao.util.ResponseResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final AuthService authService;

    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @PostMapping("/login")
    public ResponseResult<JwtAuthResponse> login(@RequestBody LoginDto loginDto){
        try {
            // 调用服务层登录，认证失败会抛出 BadCredentialsException
            String token = authService.login(loginDto);
            JwtAuthResponse response = new JwtAuthResponse();
            response.setAccessToken(token);
            return ResponseResult.okResult(response); // 成功返回 JWT
        } catch (Exception e) {
            // 认证失败（用户名/密码错误），返回错误提示
            e.printStackTrace();
            return ResponseResult.errorResult(500,"用户民或密码错误");
        }
    }

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody RegisterDto registerDto){
        String response = authService.register(registerDto);
        return new ResponseEntity<>(response, HttpStatus.CREATED);
    }
}
